<?php

!defined('IN_HC') && exit('Misquoted');

/**
 * Common library
 */
class common
{
    /**
     * 跑步等级数组
     * @var array
     */
    static public $runLevel = array(
            1 => array('level'=> 1, 'title'  => '初跑者','min'   => 0,'spacing' => 20),
            2 => array('level'=> 2, 'title'  => '小菜鸟','min'   => 20,'spacing' => 30),
            3 => array('level'=> 3, 'title'  => '大菜鸟','min'   => 50,'spacing' => 50),
            4 => array('level'=> 4, 'title'  => '初级健人','min'   => 100,'spacing' => 100),
            5 => array('level'=> 5, 'title'  => '中级健人','min'   => 200,'spacing' => 100),
            6 => array('level'=> 6, 'title'  => '高级健人','min'   => 300,'spacing' => 100),
            7 => array('level'=> 7, 'title'  => '高手','min'   => 400,'spacing' => 100),
            8 => array('level'=> 8, 'title'  => '达人','min'   => 500,'spacing' => 100),
            9 => array('level'=> 9, 'title'  => '健圣','min'   => 600,'spacing' => 200),
            10 => array('level'=> 10, 'title'  => '神马','min'   => 800,'spacing' => 200),
            11 => array('level'=> 11, 'title'  => '高级神马','min'   => 1000,'spacing' => 500),
            12 => array('level'=> 12, 'title'  => '特级神马','min'   => 1500,'spacing' => 500),
            13 => array('level'=> 13, 'title'  => '跑神','min'   => 2000,'spacing' => 1000),
            14 => array('level'=> 14, 'title'  => '超级跑神','min'   => 3000,'spacing' => 1000),
            15 => array('level'=> 15, 'title'  => '无敌跑神','min'   => 4000,'spacing' => 4000),
            16 => array('level'=> 16, 'title'  => '跑尊','min'   => 8000,'spacing' => 7000),
            17 => array('level'=> 17, 'title'  => '跑仙','min'   => 15000,'spacing' => 10000),
            18 => array('level'=> 18, 'title'  => '宇宙跑霸','min'   => 25000,'spacing' => 25000)
        );
    static public $downUrl = array(
        'iphone' => 'http://itunes.apple.com/cn/app/id869299193?ls=1&mt=8',
        // 'iphone' => 'https://itunes.apple.com/cn/app/ai-pao/id789622711?mt=8',
    );
    /**
     * 应用市场渠道
     * @var array
     */
    static public $publishChannel = array(
            'index'    => 'default',                // 非渠道
            'hupucom'    => '虎扑mobile站',         // 站内渠道
            'hupuwap'    => '虎扑wap',
            'runweb'    => '跑步频道mobile站',
            'runwap'    => '跑步频道wap站',
            'weixin'    => '微信',
            'kanqiu'    => '虎扑看球',
            'umengupdate'    => '友盟',
            'gdt'       => '广点通',                       // 推广渠道包
            'fensitong'       => '粉丝通',
            'wdjcpd'       => '豌豆荚CPD',
            'wxcpd'       => '微信CPD',
            'myappcpd'       => '应用宝CPD',
            'chunhua'       => '百度春华',
            'dianqu'       => '点趣',
            'huisuoping1'       => '惠锁屏',
            'kuchuan'       => '酷传',
            'biaoai1'       => '表爱渠道1',
            'biaoai2'       => '表爱渠道2',
            'biaoai3'       => '表爱渠道3',
            'xiaomi'    => '小米',
            'mihaiwai'    => '小米海外',
            'migangtai'    => '小米港台',
            'wandoujia' => '豌豆荚',
            '360'       => '360应用助手',
            'baidu'     => '百度',
            '91'        => '91助手',
            'google'    => 'Goolge Play',
            'hiapk'     => '安卓市场',
            'hiapk2'    => '安卓市场2',
            'myapp'     => '腾讯应用宝',
            'oppo'      => 'OPPO',
            'taobao'    => '淘宝',
            'huawei'    => '华为',
            '163'       => '网易',
            'anzhi'     => '安智',
            'anzhicpd'  => '安智CPD1',
            'anzhicpd2'  => '安智CPD2',
            'uc'        => 'UC',
            'meizu'    => '魅族',
            'appchina'  => '应用汇',
            'gfan'      => '机锋',
            'lenovo'    => '联想乐商店',
            'samsung'   => '三星',
            'intel'     => 'INTEL',
            '10086'     => '10086',
            'mumayi'    => '木蚂蚁',
            'nduoa'     => 'N多',
            'crossmo'   => '十字猫',
            '3g'        => '3G',
            'eoemarket' => '优亿市场',
            'anzow'     => '安卓软件园',
            'liqucn'    => '历趣市场',
            'dangle'    => '当乐',
            'zhushou.sogou'    => '搜狗手机助手',
            'amzon'     => '亚马逊',
            'renren'    => '人人',
            'renren'    => '人人',
            'coolpad'   => '酷派',
            'anzhuoapk' => '金立',
            'dongyang1' => '东阳1',
            'dongyang2' => '东阳2',
            'daoyou1' => '道友1',
            'daoyou2' => '道友2',
            'daoyou3' => '道友3',
            'wanpushiji1' => '万普世纪1',
            'wanpushiji2' => '万普世纪2',
            'wanpushiji3' => '万普世纪3',
            'jinyanshi1' => '金岩石1',
            'jinyanshi2' => '金岩石2',
            'jinyanshi3' => '金岩石3',
            'yifeng1' => '翼锋1',
            'yifeng2' => '翼锋2',
            'yifeng3' => '翼锋3',
            'zhongyi1' => '中亿1',
            'zhongyi2' => '中亿2',
            'zhongyi3' => '中亿3',
            'qixiazi1' => '七匣子1',
            'qixiazi2' => '七匣子2',
            'qixiazi3' => '七匣子3',
            'maikerui1' => '麦可瑞1',
            'maikerui2' => '麦可瑞2',
            'maikerui3' => '麦可瑞3',
            'youmi1' => '有米1',
            'youmi2' => '有米2',
            'youmi3' => '有米3',
        );
    /**
     * 勋章数组
     */
    static public $medalNumLimit = array(0 => '无限制',
                                        1 => '一天最多一个',
                                        2 => '一周最多一个',
                                        3 => '一月最多一个',
                                        4 => '一年最多一个',
                                        5 => '一用户最多一个'
            );
    /**
     * 版块列表类型
     * @var array
     */
    static public $postListType = array(
                    '0' => 'New',      // 最新
                    '1' => 'Hot',   // 最热
                    '2' => 'Best',  // 精华
                    '3' => 'Locale', //本地
                    '4' => 'Topic', //话题
                    '5' => 'User', //个人
            );
    
    /*
     * 话题状态
     */
    static public $topicStatus = [
        '0' => '正常',
        '1' => '隐藏'
    ];
    
    /**
     * 社区消息类型
     */
    static public $bbsMsgType = array(
                    '1' => 'beReplied',     //帖子被回复
                    '2' => 'beComment',     //评论被评论
                    '3' => 'beUP',          //评论被点亮
                    '4' => 'beLiked'        //帖子被喜欢
            );
    /**
     * 跑鞋属性
     */
    static public $shoeAttr = array(
                    'shoeCat' => array('1' => '慢跑鞋','2' => '竞速鞋','3' => '马拉松鞋','4' => '越野鞋','5' => '赤足鞋'), // 类别
                    'footType' => array('2' => '正常','1' => '高足弓','3' => '低足弓/扁平足'), // 足型 (多选)
                    'footCircle' => array('1' => '正常','2' => '足内翻','3' => '足外翻'), // 适合足类 (多选)
                    'feature' => array('1' => '稳定/支撑','2' => '缓冲/减震','3' => '控制','4'=>'生活'), // 功能
                    'funcTag' => array('1' => '缓震','2' => '支撑','3' => '控制','4' => '全能','5'=>'生活'), // 选鞋功能标签
                    'level' => array('1' => '顶级','2' => '次顶级','3' => '普通'), // 选鞋层次标签
            );
    /**
     * 跑鞋属性名称
     */
    static public $shoeAttrName = array(
                    'shoeCat' => '类别',
                    'footType' => '足型',
                    'footCircle' => '适合足类',
                    'feature' => '功能',
                    'funcTag' => '选鞋功能标签',
                    'level' => '选鞋层次标签'
            );
    /**
     * 跑步数据异常类型
     */
    static public $abnorData = array(
                    '0' => '正常',
                    '1' => '速度异常',
                    '2' => '里程异常',
                    '3' => '时间异常',
            );
    
    /*
     * 比赛状态
     */
    static public $matchStatus = array(
                                    '0'=>'预览中',
                                    '1'=>'报名中',
                                    '2'=>'进行中',
                                    '3'=>'已完结',
                                    '4'=>'已隐藏'
                                );
    
    /**
     * 返回来源页的网址
     * @return string
     */
    public static function reurl()
    {
        return !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL;
    }

    /**
     * 返回页面访问类型
     * @return string
     */
    public static function method()
    {
        return $_SERVER['REQUEST_METHOD'];
    }

    /**
     * 返回当前域名
     * @return string
     */
    public static function host()
    {
        return $_SERVER['HTTP_HOST'];
    }

    /**
     * 输出对象
     * @param all $rows     需要输出的对象
     * @param bool $type    以print_r还是var_dump来输出
     * @param bool $exit    输出后是否中止
     */
    public static function pr($rows, $type = false, $exit = false)
    {
        echo '<pre>';
        $type ? var_dump($rows) : print_r($rows);
        echo '</pre>';
        $exit && exit();
    }

    /**
     * 页面跳转
     * @param string $url
     * @param bool $t 
     */
    public static function go($url, $type = false)
    {
        !$type ? header('Location:' . $url) : print('<script>window.location.href="' . $url . '"</script>');
        exit;
    }

    /**
     * 获取Reqest数据
     * @param string $vn    变量名
     * @param string $type  获取类型
     * @param string $default   默认值
     * @param bool $mysqlEncode 是否使用mysql_escape_string
     * @return string/int/array
     */
    public static function & request($vn, $type = 'G', $default = NULL, $mysqlEncode = false)
    {
        switch($type)
        {
            case 'G':
                $val = empty($_GET[$vn]) ? $default : $_GET[$vn];
                break;
            case 'P':
                $val = empty($_POST[$vn]) ? $default : $_POST[$vn];
                break;
            case 'C':
                $val = empty($_COOKIE[$vn]) ? $default : $_COOKIE[$vn];
                break;
            case 'S':
                $val = empty($_SESSION[$vn]) ? $default : $_SESSION[$vn];
                break;
            default :
                $val = empty($_REQUEST[$vn]) ? $default : $_REQUEST[$vn];
                break;
        }

        $val && !is_array($val) && $val = trim($val);

        if(!empty($val) && get_magic_quotes_gpc())
        {
            if(is_array($val))
            {
                foreach($val as $key => $v)
                {
                    $val[$key] = stripslashes($v);
                }
            }
            else
            {
                $val = stripslashes($val);
            }
        }

        if(!empty($val) && $mysqlEncode)
        {
            if(is_array($val))
            {
                foreach($val as $key => $v)
                {
                    $val[$key] = self::mysql_real_escape_string($v);
                }
            }
            else
            {
                $val = self::mysql_real_escape_string($val);
            }
        }

        return $val;
    }
    
    /**
     * 转译字符串（防mysql注入）
     * @param string $string
     * @return string
     */
    public static function mysql_real_escape_string($var)
    {
        if(!empty($var)) {
            return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $var);
        }
    }


    /**
     * 批量获取Request数据
     * @param array $cols
     * @param string $type
     * @return array
     */
    public static function multiRequest(array $cols, $type = 'G')
    {
        $result = array();

        foreach ($cols as $k => $v)
        {
            $result[$v] = common::request($v, $type);
            !is_array($result[$v]) && $result[$v] = trim($result[$v]);
        }

        return $result;
    }

    /**
     * 获取客户端IP
     * @return int(10)
     */
    public static function getip($ip2long = FALSE)
    {
        if (!empty($_SERVER["HTTP_CLIENT_IP"]))
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        else if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))
            $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        else if (!empty($_SERVER["REMOTE_ADDR"]))
            $ip = $_SERVER["REMOTE_ADDR"];
        else
            $ip = NULL;
        if ($ip && $ip2long)
            $ip = bindec(decbin(ip2long($ip)));

        return $ip;
    }

    /**
     * 将一维数组转为字符串 (array('a' => 1, 'b' => 2, 'c => '?+1') To: a=1, b=2, c=c+1)
     * @param array 需要转换的数组对象
     * @return string
     */
    public static function arrayToString(array $datas = array())
    {
        $str = NULL;

        if (!empty($datas))
        {
            $s = array('like', 'update', 'id', 'key', 'limit', 'order', 'type');

            $i = 1;
            $dataCount = count($datas);
            foreach ($datas as $key => $data)
            {
                $str .= (in_array($key, $s) ? '`' . $key . '`' : $key) . ($data && in_array($data, array('?+1', '?-1', '?+2', '?-2')) ? '=' . $key . strtr($data, array('?' => NULL)) : '=\'' . self::mysql_real_escape_string($data) . '\'') . ($i < $dataCount ? ', ' : NULL);
                $i++;
            }
        }
        return $str;
    }

    /**
     * 以HTTP方式远程获取内容
     * @param string $url
     * @param array $datas
     * @param int $timeout
     * @param string $method
     * @return string
     */
    public static function & getContents($url, $datas = array(), $timeout = 10, $method = 'GET', $contentType = NULL, $cookies = NULL)
    {
        $method = strtoupper($method);

        $query = is_array($datas) ? http_build_query($datas, NULL, '&') : $datas;

        if ($method == 'GET' && !empty($query))
        {
            $url .= '?' . $query;
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);

        if ($method == 'POST' && !empty($query))
        {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        }

        if(stripos($url,"https://")!==FALSE)
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }

        !empty($cookies) && curl_setopt($ch, CURLOPT_COOKIE, $cookies);

        if ($contentType)
        {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: " . $contentType));
        }

        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $results = curl_exec($ch);

        curl_close($ch);
        
        return $results;
    }
    
    /**
     * 对多URL地址进行GET/POST操作，并返回数据
     * @param array $urls
     * @param array||string $data
     * @param string $method
     * @param int $timeOut
     * @return array 
     */
    public static function & getMultiContents(array $urls, $data = array(), $method = 'GET', $timeOut = 3)
    {
        $responses = array();

        $queue = curl_multi_init();
        $map = array();

        $query = $data ? (is_array($data) ? http_build_query($data, NULL, '&') : $data) : '';

        foreach ($urls as $url)
        {
            $ch = curl_init();

            if ($query)
            {
                if ($method == 'GET')
                {
                    $url .= '?' . $query;
                } else
                {
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
                }
            }

            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeOut);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_NOSIGNAL, true);

            curl_multi_add_handle($queue, $ch);
            $map[(string) $ch] = $url;
        }

        do {
            while (($code = curl_multi_exec($queue, $active)) == CURLM_CALL_MULTI_PERFORM);

            if ($code != CURLM_OK)
            {
                break;
            }

            while ($done = curl_multi_info_read($queue)) {

                $info = curl_getinfo($done['handle']);
                $info = array('http_code' => $info['http_code']);
                $error = curl_error($done['handle']);
                $error && $info['error'] = $error;
                $result = curl_multi_getcontent($done['handle']);
                $responses[$map[(string) $done['handle']]] = compact('info', 'result');

                curl_multi_remove_handle($queue, $done['handle']);
                curl_close($done['handle']);
            }

            if ($active > 0)
            {
                curl_multi_select($queue, 0.5);
            }
        } while ($active);

        curl_multi_close($queue);

        return $responses;
    }

    /**
     * 并发获取多个URL的内容
     * @param array $urls
     * @param int $timeount
     * @return array 
     */
    public static function getUrlsContent($urls, $timeount = 3, $encodeUrl = TRUE)
    {
        $responses = array();

        if (!empty($urls))
        {
            !is_array($urls) && $urls = array($urls);

            $queue = curl_multi_init();
            $map = array();

            foreach ($urls as $url)
            {
                $ch = curl_init();

                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_TIMEOUT, $timeount);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_NOSIGNAL, true);

                curl_multi_add_handle($queue, $ch);
                $map[(string) $ch] = $url;
            }

            do {
                while (($code = curl_multi_exec($queue, $active)) == CURLM_CALL_MULTI_PERFORM);

                if ($code != CURLM_OK)
                {
                    break;
                }

                while ($done = curl_multi_info_read($queue)) {
                    $info = curl_getinfo($done['handle']);
                    $info = array('http_code' => $info['http_code'], 'total_time' => $info['total_time']);
                    $error = curl_error($done['handle']);
                    !empty($error) && $info['error'] = $error;
                    $result = curl_multi_getcontent($done['handle']);

                    $k = $encodeUrl ? md5($map[(string) $done['handle']]) : $map[(string) $done['handle']];
                    $responses[$k] = compact('info', 'result');

                    curl_multi_remove_handle($queue, $done['handle']);
                    curl_close($done['handle']);
                }

                if ($active > 0)
                {
                    curl_multi_select($queue, $timeount);
                }
            } while ($active);

            curl_multi_close($queue);
        }

        return $responses;
    }

    /**
     * 开启页面Gzip
     * @param string $content
     * @return string 
     */
    public static function ob_gzip($content)
    {
        if (!headers_sent() && extension_loaded("zlib") && !empty($_SERVER["HTTP_ACCEPT_ENCODING"]) && strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip"))
        {
            header('Content-type:application/json;charset=utf-8');

            $content = gzencode($content, 9);

            header("Content-Encoding: gzip");
            header("Vary: Accept-Encoding");
            header("Content-Length: " . strlen($content));
        }

        return $content;
    }

    /**
     * 版本号对比
     * @param string $version1
     * @param string $version2
     * @return boolean
     */
    public static function diffVersion($version1, $version2)
    {
        $version1 = common::versionToNumber($version1);
        $version2 = common::versionToNumber($version2);

        return $version1 > $version2;
    }

    /**
     * 将版本号转换为数字
     * @param string $version
     * @return int
     */
    public static function versionToNumber($version)
    {
        $number = 0;

        !$version && $version = '0.0.0';
        $vTmp = explode('.', $version);

        if (count($vTmp) >= 3)
        {
            foreach ($vTmp as $k => $v)
            {
                if (!is_numeric($v))
                {
                    $number = 0;

                    break;
                } else
                {
                    switch ($k) 
                    {
                        case 0:
                            $number += 1000 * $v;
                            break;
                        case 1:
                            $number += 100 * $v;
                            break;
                        case 2:
                            $number += 10 * $v;
                            break;
                        default:
                            $number += 0;
                            break;
                    }
                    // $number += intval($v) << (16 - $k * 8);
                }
            }
        }

        return $number;
    }

    /**
     * 格式化在线人数
     * @param int $num 
     */
    public static function formatOnlineNum($num)
    {
        $num = is_numeric($num) ? intval($num) : 1;
        $num > 90 && $num = $num * 9;
        $num < 10000 && $newNum = $num;
        ($num >= 10000 && $num < 100000) && $newNum = round($num / 10000, 1) . '万';
        $num >= 100000 && $newNum = ceil($num / 10000) . '万';

        return $newNum;
    }

    /**
     * 与微博一样的计算字符长度（1个汉字算1个字，1个字母或数字，算0.5个字）
     * @param string $content
     * @return int
     */
    public static function weiboStrlen($content)
    {
        preg_match_all("/[\x80-\xff]/", $content, $cn);

        $i = mb_strlen($content, 'utf-8');
        $j = !empty($cn[0]) ? count($cn[0]) / 3 : 0;

        $i = ($i - $j) / 2 + $j;

        return $i;
    }

    /**
     * 组装地址
     * @param type $urlArray
     * @return string
     */
    public static function packUrl($urlArray)
    {

        if (empty($urlArray['query']))
        {
            $path = (isset($urlArray["path"]) ? $urlArray["path"] : "");
        } else
        {
            $path = (isset($urlArray["path"]) ? $urlArray["path"] : "/");
        }

        $url = (isset($urlArray["scheme"]) ? $urlArray["scheme"] . "://" : "") .
                (isset($urlArray["user"]) ? $urlArray["user"] . ":" : "") .
                (isset($urlArray["pass"]) ? $urlArray["pass"] . "@" : "") .
                (isset($urlArray["host"]) ? $urlArray["host"] : "") .
                (isset($urlArray["port"]) ? ":" . $urlArray["port"] : "") .
                $path .
                (!empty($urlArray['query']) ? "?" . http_build_query($urlArray['query']) : "") .
                ( isset($urlArray["fragment"]) ? "#" . $urlArray["fragment"] : "");

        return $url;
    }

    /**
     * 将内容中的HTML实体替换为字符串
     * @param array $data
     * @return string
     */
    public static function pregReplaceContentHtmlToString($data)
    {
        return common::htmlEntitiesToString($data[0]);
    }

    public static function getHashStr($length = 6)
    {
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        $hash = '';
        for ($i = 0; $i < $length; $i++)
        {
            $hash .= $chars[mt_rand(0, 61)];
        }

        return $hash;
    }

    /**
     * 将HTML实体替换为字符串
     * @param string $str
     * @return string
     */
    public static function htmlEntitiesToString($str)
    {
        return mb_convert_encoding($str, 'utf-8', 'HTML-ENTITIES');
    }
    /**
     * 安全的Base64编码
    */
    public static function urlsafe_base64_encode($str) // URLSafeBase64Encode
    {
        $find = array('+', '/');
        $replace = array('-', '_');
        return str_replace($find, $replace, base64_encode($str));
    }
    /**
     * @param string $mileage 跑步里程 单位:公里
     * @return int
     */
    public static function getLevel($mileage)
    {
        $levelArr = self::$runLevel;
        for($level =1; $level<= count($levelArr); $level++)
        {
            if($mileage >=$levelArr[$level]['min'] && $mileage< $levelArr[$level]['min'] + $levelArr[$level]['spacing'])
            {
                return $level;
                break;
            }
        }
        return 15;
    }
    /**
     * 创建多层目录
     * @param type $dir
     * @param type $mode
     * @return type
     */
    public static function mkdirs($dir, $mode = 0777)
    {
        return is_dir($dir) or (self::mkdirs(dirname($dir)) and mkdir($dir, $mode));
    }

    /**
     * 返回图片的绝对url地址
     * @param type $path
     * @return type
     */
    public static function realUrl($path)
    {
        return empty($path) ? '' : 'http://' . self::host() . '/static/'.$path;
    }

    /**
     * 秒转为*小时*分钟*秒
     * @param type $sec
     * @return string
     */
    public static function sec2time($seconds)
    {
        $mins = round($seconds / 60); // 分钟数
        if ($mins >= 60)
        {
            $hour = floor($mins / 60);
            $min = $mins % 60;

            $res = $hour . ' 小时 ';
            $min != 0 && $res .= $min . '分钟';
        }
        else
        {
            $res = $mins . '分钟';
        }   

        $sec = $seconds % 60;
        $sec != 0 && $res .= $sec .'秒';

        return $res;
    }
    /**
     * 格式化秒数为  xx:xx:xx
     * @param type $sec
     * @return string
     */
    public static function sec2format($sec)
    {
        $m = floor($sec / 60);
        $h = floor($m / 60);
        $m = $m%60;
        $s = $sec%60;
        if($h > 1 && $h < 10)
        {
            $h = '0'.$h;
        }
        else if($h == 0)
            $h = '00';
        if($m > 1 && $m < 10)
        {
            $m = '0'.$m;
        }
        else if($m == 0)
            $m = '00';
        if($s > 1 && $s < 10)
        {
            $s = '0'.$s;
        }
        else if($s == 0)
            $s = '00';
        return $h.':'.$m.':'.$s;
    }

    /**
     * 格式化 分钟'秒''
     */
    public static function sec3format($timestamp) {
        $min = floor($timestamp/60);
        strlen($min) == 1 && $min = '0'.$min;
        $sec = $timestamp%60;
        strlen($sec) == 1 && $sec = '0'.$sec;
        return $min."'".$sec."''";
    }

    /**
     *  获取年周数
     * @param type $time
     * @return string
     */
    public static function getWeekth($time=0)
    {
        empty($time) && $time = time();
        $year = date("Y", $time);
        $month = date("m", $time);
        $week = date("W", $time);
        ($week == 1 && $month == 12) && $year += 1;

        // return $year.'-W'.$week;
        return $year.$week;
    }
    /**
     *  获取一周日期范围
     * @param type $time
     * @return string
     */
    public static function getWeekRange($time=0)
    {
        empty($time) && $time = time();
        $time = strtotime(date("Y-m-d", $time));
        $week = date("N", $time);

        $monday = $time - ($week - 1) * 86400;
        $sunday = $time + (7-$week) * 86400;
        return compact('monday','sunday');
    }
    /**
     * 返回是否是json
     * @param type $str
     * @return type
     */
    public static function is_json($str)
    {
        return !is_null(json_decode($str));
    }

    public static function dpb()
    {
        echo '<pre>';
        debug_print_backtrace();
        echo '</pre>';
    }

    /**
     * 日志记录
     * @param  [type] $content  [记录内容]
     * @param  string $fileName [日志文件名称]
     * @param  string $folder   [日志文件目录]
     * @return [type]           [description]
     */
    public static function log($content, $fileName = 'log', $folder = 'default'){
        //文件所处目录
        $path = '/data/log-data/irun/' . $folder . "/";
        //查看文件目录是否存在,不存在创建
        !file_exists($path) && mkdir($path);
        //文件名称及类型
        $logName = $fileName.'.txt';
        //写入方式打开，将文件指针指向文件末尾。如果文件不存在则尝试创建之。
        $fp = fopen($path.$logName, "a");
        //文件内容前缀
        $log_prefix = '---start---'.date('Y-m-d H:i:s')."---\n";
        //文件内容后缀
        $log_suffix = '---end---'.date('Y-m-d H:i:s')."---\n";
        //写入内容
        fwrite($fp, $log_prefix . $content . "\n" . $log_suffix);
        //写入换行
        fwrite($fp, "\n");
        //关闭
        fclose($fp);
    }



    

    public  static function add_url_param($url, $key, $value) {
        $url=preg_replace('/(.*)(?|&)'.$key.'=[^&]+?(&)(.*)/i','$1$2$4',$url.'&');
        $url=substr($url,0,-1);
        if(strpos($url,'?') === false){
            return ($url.'?'.$key.'='.$value);
        } else {
            return ($url.'&'.$key.'='.$value);
        }
    }

    /**
    *格式化时间差
    */
    static public function timediff($diff,$for='post'){
        if($for=='run'){
            if($diff <= 3600){
                return '1小时内';
            }elseif($diff > 3600 && $diff <=86400){
                return ceil($diff/3600).'小时前';
            }elseif($diff > 86400 && $diff <= 172800){
                return '昨天';
            }elseif($diff > 172800 && $diff <= 259200){
                return '前天';
            }elseif($diff > 259200 && $diff <= 604800){
                return ceil($diff/86400).'天前';
            }elseif($diff >604800 && $diff <= 2678400){
                return ceil($diff/604800).'周前';
            }elseif($diff > 2678400 && $diff <= 31536000){
                return ceil($diff/2678400).'个月前';
            }else{
                return ceil($diff/31536000).'年前';
            }
        }elseif($for == 'paome'){
            if($diff <= 3600){
                return ceil($diff/60).'分钟前';
            }elseif($diff > 3600 && $diff <=86400){
                return ceil($diff/3600).'小时前';
            }elseif($diff > 86400 && $diff <= 172800){
                return '昨天';
            }elseif($diff > 172800 && $diff <= 604800){
                return ceil($diff/86400).'天前';
            }
        }else{
            if($diff <= 1800){
                return '刚刚';
            }elseif($diff > 1800 && $diff <= 3600){
                return '半小时前';
            }elseif($diff > 3600 && $diff <=86400){
                return ceil($diff/3600).'小时前';
            }elseif($diff > 86400 && $diff <= 172800){
                return '昨天';
            }elseif($diff > 172800 && $diff <= 259200){
                return '前天';
            }elseif($diff > 259200 && $diff <= 604800){
                return ceil($diff/86400).'天前';
            }elseif($diff >604800 && $diff <= 2678400){
                return ceil($diff/604800).'周前';
            }elseif($diff > 2678400 && $diff <= 31536000){
                return ceil($diff/2678400).'个月前';
            }else{
                return ceil($diff/31536000).'年前';
            }
        }
    }

    /**
     * 是否在App的内置浏览器中
     * @return boolean
     */
    static public function isInAppWebview()
    {
        $result = FALSE;
        $ua = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : NULL;

        $ua && stripos($ua, 'Joggers') !== FALSE && $result = TRUE;

        //安卓没有ua，临时判断为true
        if($ua === NULL){
            $result = true;
        }
        return $result;
    }

    /**
     * 获取设备类型
     */
    public static function getOs()
    {
        $userAgent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : NULL;

        $os = 'android';

        if(stristr($userAgent, 'iphone') !== FALSE || stristr($userAgent, 'ipad') !== FALSE || stristr($userAgent, 'ipod') !== FALSE)
        {
            $os = 'ios';
        }

        return $os;
    }
    
    /*
     * 判断是否移动设备
     */
    public static function is_mobile() {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $mobile_browser = Array(
            "mqqbrowser", //手机QQ浏览器
            "opera mobi", //手机opera
            "juc","iuc",//uc浏览器
            "fennec","ios","applewebKit/420","applewebkit/525","applewebkit/532","ipad","iphone","ipaq","ipod",
            "iemobile", "windows ce",//windows phone
            "240×320","480×640","acer","android","anywhereyougo.com","asus","audio","blackberry","blazer","coolpad" ,"dopod", "etouch", "hitachi","htc","huawei", "jbrowser", "lenovo","lg","lg-","lge-","lge", "mobi","moto","nokia","phone","samsung","sony","symbian","tablet","tianyu","wap","xda","xde","zte"
        );
        $is_mobile = false;
        foreach ($mobile_browser as $device) {
            if (stristr($user_agent, $device)) {
                $is_mobile = true;
            break;
            }
        }
        return $is_mobile;
    }

    /**
     * js页面跳转
     * @param $message
     * @param string $url
     */
    public static function tips($message,$url=''){
        $html = "<div>{$message}<span id='time'>3</span>秒后将返回！</div>";
        $str = <<<EOT
            <script>
                document.write("$html");
                window.onload = function(){
                    setInterval(function(){
                        var time = document.getElementById('time');
                        var url = "$url";
                        var t = parseInt(time.innerHTML);
                        if(t > 1){
                            t--;
                            time.innerHTML = t;
                            console.info(t);
                        }else{
                            if(url == ''){
                                window.history.go(-1);
                            }else{
                                window.location.href = url;
                            }
                        }
                    },1000)


                }
            </script>
EOT;

        echo $str;
    }

    /**
     * 手机号码验证
     * @param $phone
     * @return bool
     */
    public static function checkPhone($phone)
    {
        $result = FALSE;

        if(!empty($phone) && preg_match('/^1\d{10}$/', $phone))
        {
            $phoneFix = array('133', '153', '180', '181', '189', '1349', '130', '131', '132', '155', '156', '185', '186', '134', '135', '136', '137', '138', '139', '147', '150', '151', '152', '157', '158','159', '170', '176', '178', '177', '182', '187', '188', '183', '184', '145', '1709', '154', '165');

            foreach ($phoneFix as $pk => $pv)
            {
                if(strpos($phone, $pv) !== FALSE)
                {
                    $result = TRUE;
                    break;
                }
            }
        }

        return $result;
    }

    /**
     * 是否在微信浏览器中访问
     * @return boolean
     */
    public static function isInWeixin()
    {
        $ua = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : NULL;

        return $ua ? stripos($ua, 'MicroMessenger') !== FALSE : FALSE;
    }
    
    /*
     * 根据url判断电商名称
     */
    static public function detectShop($url){
        $arr = [
            'tmall.com'=>'天猫',
            'taobao.com'=>'淘宝',
            'jd.com'=>'京东',
            '360buy.com'=>'京东',
            'z.cn'=>'亚马逊',
            'amazon.com'=>'亚马逊',
            'amazon.cn'=>'亚马逊'
        ];
        foreach($arr as $key=>$name){
            if(stripos($url,$key)!==false){
                return $name;
            }
        }
        return '';
    }
    
    //正能量
    static public $energySet = array('comment' => array('energy' =>2, 'limit' => 5, 'description' => "您在跑友秀发表评论"),
                                'run' => array('energy' =>1, 'limit' => 3, 'description' => "了不起，您本次跑了%s公里"),
                                'target' => array('energy' =>2, 'limit' => 3, 'description' => "了不起，您本次跑了%s公里，并完成设定目标"),
                                'share' => array('energy' =>3, 'limit' => 3, 'description' => "和小伙伴分享运动的喜悦"),
                                'new' => array('energy' =>100, 'limit' => 1, 'description' => "欢迎加入虎扑跑步"),
                                'upgrade' => array('energy' =>100, 'limit' => 1, 'description' => '感谢您对虎扑跑步的支持'),
                                'post' => array('energy' =>5, 'limit' => 5, 'description' => '系统奖励5点正能量'),
                                'pay' => array('description' => '正能量鼓励其他跑友'),
                                'paid' => array('description' => '获得跑友鼓励正能量'),
                                'createActivity' => array('energy' => 3, 'limit'=>3, 'description' => '发布活动'),
                                'joinActivity' => array('energy' => 2, 'limit'=>6,'description'=>'参加活动'),
                                'shareActivity' => array('energy'=>1,'limit'=>5,'description'=>'分享活动'),
                                'paomeCreateClub' => array('energy'=>100,'description'=>'跑么杯创建战队'),
                                'paomePay' => array('description'=>'正能量鼓励其他跑友'),
                                'paomePaid' => array('description'=>'获得跑友鼓励正能量'),
                                'careMonster' => array('energy'=>5,'description'=>'给宠物恢复了体力'),
                                'gameGift' => array('description'=>'宠物战斗获取正能量')
                                );

    //体重秤
    static public  $scaleWeight = array(
        array(
            'id'=>1000,
            'name'=>'云康宝体重秤',
            'Link'=>'http://detail.koudaitong.com/show/goods?alias=1y6h09rm44szw&v2/goods/1y6h09rm44szw'
        )
    );
    
    //订单状态
    static public $orderStatus = [
        1 => '等待发货',
        2 => '已发货',
        3 => '已取消',
        4 => '已完结'
    ];
    
    //支付装态
    static public $payStatus = [
        '10'=>'等待付款',
        '20'=>'已付款',
        '30'=>'退款中',
        '40'=>'已退款'
    ];


    //跑么杯状态
    static public $pmCupStatus = [
        0=>'赛季未开始',
        1=>'第一轮招募期',
        5=>'第一轮预赛进行中',
        6=>'第一轮预赛结束空档期（22点到24点）',
        10=>'第一轮决赛进行中',
        11=>'第一轮决赛结束空档期（22点到24点）',
        12=>'第一轮休赛期',
        15=>'第二轮预赛进行中',
        16=>'第二轮预赛结束空档期（22点到24点）',
        20=>'第二轮决赛进行中',
        21=>'第二轮决赛结束空档期（22点到24点）',
        22=>'第二轮休赛期',
        25=>'第三轮预赛进行中',
        26=>'第三轮预赛结束空档期（22点到24点）',
        30=>'第三轮决赛进行中',
        31=>'第三轮决赛结束空档期（22点到24点）',
        32=>'第三轮休赛期',
        105=>'冠军争霸赛进行中',
        106=>'冠军赛结束空档期（22点到24点）',
        120=>'赛事结束'
    ];

    //战队人数不能变更的状态
    static public $pmClubNumNotStatus =[
        10,11,20,21,30,31,105,106
    ];

    //战队不能解散的状态
    static public $pmClubNotKillStatus = [
        5,6,10,11,15,16,20,21,25,26,30,31,105,106
    ];

    //可以上传跑步记录的时间赛季状态
    static public $arrCanLoadStatus = [
        5,6,10,11,15,16,20,21,25,26,30,31,105,106
    ];

    //跑步记录有效状态,比赛中 key 阶段id value 各阶段进行中主状态 第N轮预选赛进行中、决赛进行中 争霸赛进行中
    static public $arrValidStatus = [1=>5,5=>10,10=>15,15=>20,20=>25,25=>30,100=>105];

    //客户端战队详情 战队轮次阶段文字描述
    static public  $arrStatusMsg = [
                                        1=>'第一轮预选赛',
                                        5=>'第一轮冠军赛',
                                        10=>'第二轮预选赛',
                                        15=>'第二轮冠军赛',
                                        20=>'第三轮预选赛',
                                        25=>'第三轮冠军赛',
                                        100=>'争霸赛'
                                    ];

    //订单类型
    static public $actType = [
        '0' => '群组活动',
        '1' => '赛事',
        '2' => '马拉松',
        '5' => '闪购',
        '6' => '微课报名',
        '7' => '微课充值',
        '8' => '海淘'
    ];

    /*
     * 跑么杯--赛季阶段与跑步轮次对应字典
     */
    static public $roundsDict = array(
        1 => array(5, 6, 10, 11, 12),
        5 => array(15, 16, 20, 21, 22),
        10 => array(25, 26, 30, 31,32),
        100 => array(105,106,120)
    );

    /*
     * 跑么杯--赛事资格轮次字典
     */
    static public $clubStatusRound = array(
        1 => array(1, 5),
        5 => array(10, 15),
        10 => array(20, 25),
        100 => array(100)
    );
    
    /*
     * 勋章分类
     */
    static public $medalCate = [
        1 => '星星征途',
        2 => '荣誉时刻',
        3 => '蜕变历程'
    ];
    
    /*
     * 闪购装态
     */
    static public $flashSaleStatus = [
        '0' => '未开始',
        '-5' => '已删除',
        '5' => '进行中',
        '10' => '已结束'
    ];

    /**
     * 直播状态
     */
    static public $liveStatus = [
        '0' => '未开始',
        '-5' => '已取消',
        '5' => '直播中',
        '10' => '已结束'
    ];

    /**
     * 礼物列表
     */
    static public $giftList = [
        1=>array('id'=>1, 'name'=>'游艇', 'imageUrl'=>'', 'goldNum'=>0, 'price'=>0),
        2=>array('id'=>2, 'name'=>'皮鞭', 'imageUrl'=>'', 'goldNum'=>0, 'price'=>0),
        3=>array('id'=>3, 'name'=>'润喉糖', 'imageUrl'=>'', 'goldNum'=>0, 'price'=>0),
        4=>array('id'=>4, 'name'=>'花束', 'imageUrl'=>'', 'goldNum'=>0,'price'=>0)
    ];

    /**
     * 小元宝
     */
    static public $goldConfiguration = [
        1=>array('id'=>1, 'costPrice'=>6, 'goldNum'=>60, 'giveNum'=>0, 'tips'=>'' , 'applePid'=>'com.hupu.joggers.yuanbao01'),
        2=>array('id'=>2, 'costPrice'=>18, 'goldNum'=>180, 'giveNum'=>0, 'tips'=>'', 'applePid'=>'com.hupu.joggers.yuanbao02'),
        3=>array('id'=>3, 'costPrice'=>50, 'goldNum'=>500, 'giveNum'=>0, 'tips'=>'', 'applePid'=>'com.hupu.joggers.yuanbao03'),
        4=>array('id'=>4, 'costPrice'=>108, 'goldNum'=>1080, 'giveNum'=>25, 'tips'=>'现在充值，多送25小元宝', 'applePid'=>'com.hupu.joggers.yuanbao04'),
        5=>array('id'=>5, 'costPrice'=>518, 'goldNum'=>5180, 'giveNum'=>188, 'tips'=>'现在充值，多送188小元宝', 'applePid'=>'com.hupu.joggers.yuanbao05'),
        6=>array('id'=>6, 'costPrice'=>1218, 'goldNum'=>12180, 'giveNum'=>518, 'tips'=>'现在充值，多送518小元宝', 'applePid'=>'com.hupu.joggers.yuanbao06')
    ];
}

?>
